import json
import logging
from datetime import datetime
import threading
import asyncio
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from lapi_app.models.bug_model.bug import Bug, Bug_menu
from lapi_app.models.user_model.user_info import Userinfo
from lapi_app.view.bug_view.bug_email import send_email

logger = logging.getLogger('django')


def bug_list(request):
    try:
        data = json.loads(request.body)
        project_id = data["project_id"]
        result = []
        size_page = data["size_page"]
        current_pages = data["current_page"]
        bug = Bug.objects.filter(~Q(bug_status=0), bug_menu_id=project_id, bug_name__contains=data["bug_name"])
        if data["select_time"]:
            bug = bug.filter(create_time__range=(data["select_time"][0], data["select_time"][1]))
        if data["username_select"] != "":
            bug = bug.filter(deal_user=data["username_select"])
        bug = bug.order_by('-id')
        menu = Bug_menu.objects.get(id=project_id)
        username = menu.m_user.username
        prd = menu.project_prd
        create_time = menu.create_time
        update_time = menu.update_time
        bug_total = len(bug)
        for i in bug:
            bug_dict = {
                "id": i.id,
                "bug_name": i.bug_name,
                "bug_severity": i.bug_severity,
                "bug_status": i.bug_status,
                "bug_content": i.bug_content,
                "bug_urgency": i.bug_urgency,
                "create_time": datetime.strftime(i.create_time, "%Y-%m-%d %H:%M:%S"),
                "update_time": datetime.strftime(i.update_time, "%Y-%m-%d %H:%M:%S"),
                "deal_user": Userinfo.objects.get(id=i.deal_user).username,
                "deal_user_id": i.deal_user,
                "username": i.user.username
            }
            result.append(bug_dict)
        p = Paginator(result, size_page)
        page1 = p.page(current_pages)
        current_page = page1.object_list
        return JsonResponse({
            "code": 200,
            "content": current_page,
            "bug_total": bug_total,
            "size_page": size_page,
            "current_page": current_pages,
            "create_username": username,
            "project_prd": prd,
            "create_time": datetime.strftime(create_time, "%Y-%m-%d %H:%M:%S"),
            "update_time": datetime.strftime(update_time, "%Y-%m-%d %H:%M:%S")
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def add_bug(request):
    try:
        data = json.loads(request.body)
        menu_id = data["id"]
        bug_content = data["bug_content"]
        bug_name = data["bug_name"]
        bug_severity = data["bug_severity"]
        bug_urgency = data["bug_urgency"]
        deal_user_id = data["deal_user_id"]
        user_id = data["user_id"]
        if menu_id == "" or bug_content == "" or bug_name == "" or bug_severity == "" or bug_urgency == "" or deal_user_id == "" or user_id == "":
            return JsonResponse({
                "code": 100,
                "message": "必要参数不可以为空"
            })
        else:
            if data["action"] == 1:
                Bug.objects.filter(id=data["bug_id"]).update(bug_menu_id=menu_id, bug_content=bug_content,
                                                             bug_name=bug_name,
                                                             bug_severity=bug_severity, bug_urgency=bug_urgency,
                                                             deal_user=deal_user_id, updater_user=user_id,
                                                             bug_status=data["bug_status"],
                                                             update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                return JsonResponse({
                    "code": 200,
                    "message": "编辑成功"
                })
            else:
                bug = Bug.objects.create(bug_menu_id=menu_id, bug_content=bug_content, bug_name=bug_name,
                                         bug_severity=bug_severity, bug_urgency=bug_urgency,
                                         deal_user=deal_user_id, user_id=user_id, bug_status=1, updater_user=user_id)
                user = Userinfo.objects.get(id=user_id)
                re_user = Userinfo.objects.get(id=deal_user_id)
                # 多线程执行邮件通知
                # t = threading.Thread(target=bug_email(user.username, user.email, re_user.email, user.email_password, bug.bug_name))
                # t.start()
                
                # 异步发送邮件通知
                asyncio.run(send_email(username=user.username, email=user.email, re_email=re_user.email, password=user.email_password, bug_name=bug.bug_name))
                return JsonResponse({
                    "code": 200,
                    "message": "创建成功"
                })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def del_bug(request):
    try:
        data = json.loads(request.body)
        id = data["id"]
        Bug.objects.filter(id=id).update(bug_status=0)
        return JsonResponse({
            "code": 200,
            "message": "删除成功"
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })
